/*
 * Copyright (C) 2016 Facishare Technology Co., Ltd. All Rights Reserved.
 */
package floatWindow2.rom;

import android.annotation.TargetApi;
import android.app.AppOpsManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.os.PowerManager;
import android.provider.Settings;
import android.util.Log;
import android.view.Gravity;
import android.widget.Toast;

import com.example.livesettingtest.KeepLivingSettingsForOPPO;
import com.example.livesettingtest.MyConstant;
import com.example.livesettingtest.R;

import java.lang.reflect.Method;

import floatWindow2.FloatActionController;

import static android.content.Context.POWER_SERVICE;

public class OppoUtils {
    private static final String TAG = "OppoUtils";
    static Context mContext;

    public static OppoUtils getInstance(Context context) {
        mContext = context;
        return OppoUtils.LittleMonkProviderHolder.sInstance;
    }

    // 静态内部类
    private static class LittleMonkProviderHolder {
        private static final OppoUtils sInstance = new OppoUtils();
    }

    /**
     * 引导用户打开所有权限 或通知
     * @param tipType
     * @param isPermission
     */
    public void openPermission(MyConstant.tipType tipType, boolean isPermission) {

        Intent intent = new Intent();
        intent.setData(Uri.parse("package:" + mContext.getPackageName()));
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
      //GXW-  intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

        try {

            if(tipType == MyConstant.tipType.OPPO_OPEN_PERMISSION) {
                Log.i(TAG,"OPPO_OPEN_PERMISSION");
                Toast toast = Toast.makeText(mContext,R.string.oppo_open_permission, Toast.LENGTH_LONG);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
            }

            else if(tipType == MyConstant.tipType.PERMISSION_NOTIFY)
            {
                 //操作指引提示 打开通知
            }

            mContext.startActivity(intent);
            openFloatWindowTip(tipType,isPermission);
        } catch (Exception e) {
            dealErrorSkip(e);
        }
        return;
    }



    /**
     * 如果跳转错误，让其应用跳转到系统设置页面。
     * @param e
     */

    public void dealErrorSkip(Exception e) {

        Toast.makeText(mContext, R.string.page_skip_failed, Toast.LENGTH_SHORT).show();
        e.printStackTrace();
        Log.i(TAG, e.getMessage());
        Intent intent = new Intent(Settings.ACTION_SETTINGS);
        mContext.startActivity(intent);
    }
    /**
     * OPPO耗电保护，冻结，异常耗电，深度睡眠等三个开关关闭
     * @param isPermissionFloat
     */
    public void  batteryProtected(boolean isPermissionFloat)
    {
        //耗电保护
        try
        {
            Intent intent = new Intent();
            ComponentName componentName = null;
            String packName = mContext.getPackageName();
            componentName = new ComponentName("com.coloros.oppoguardelf", "com.coloros.powermanager.fuelgaue.PowerConsumptionActivity");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setComponent(componentName);
            mContext.startActivity(intent);
            openFloatWindowTip(MyConstant.tipType.OPPO_BATTERY_PROTECT,isPermissionFloat);
        }catch (Exception e)
        {
            dealErrorSkip(e,MyConstant.tipType.OPPO_BATTERY_PROTECT,isPermissionFloat);
        }

    }

    /**
     * 自启动，关联启动
     */
    public void autoStart(boolean isPermissionFloat)
    {
        try {
            Intent intent = new Intent();
            ComponentName componentName = null;
            String packName = mContext.getPackageName();
            componentName = new ComponentName("com.coloros.safecenter", "com.coloros.privacypermissionsentry.PermissionTopActivity");
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            intent.setComponent(componentName);
            mContext.startActivity(intent);
            openFloatWindowTip(MyConstant.tipType.OPPO_AUTO_ASSIGN,isPermissionFloat);
        }catch (Exception e)
        {
            dealErrorSkip(e);
        }

        return;
    }



    public void dealErrorSkip(Exception e, MyConstant.tipType type, boolean permissionFloat) {
        try
        {
            Log.i(TAG, "跳转异常了");
          //GXW-  toastTip(R.string.vivo_settings_permission);
            e.printStackTrace();
            Log.i(TAG, e.getMessage());
            Intent intent = new Intent(Settings.ACTION_SETTINGS);
            mContext.startActivity(intent);

            switch (type)
            {
                case OPPO_BATTERY_PROTECT:
                    openFloatWindowTip(MyConstant.tipType.OPPO_BATTERY_PROTECT_HIGH_OS,permissionFloat);
                    break;
            }
        }
        catch (Exception e1)
        {
            e1.printStackTrace();
        }
    }

    public void toastTip(int tipResId)
    {
        Toast toast = Toast.makeText(mContext,tipResId, Toast.LENGTH_LONG);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }

    /**
     * 打开浮动窗口
     */
    static public void openFloatWindowTip( MyConstant.tipType floatWindowType, boolean isPermission) {

        //有对应权限或者系统版本小于7.0
        if (isPermission || Build.VERSION.SDK_INT < 24) {  //gxw:也就是android 6.0及以下，这里需要在6.0以下的手机上测试一下
            //开启悬浮窗
            FloatActionController.getInstance().startMonkServer(mContext,floatWindowType);
        }

        return;
    }



    @TargetApi(Build.VERSION_CODES.KITKAT)
    private static boolean checkOp(Context context, int op) {
        final int version = Build.VERSION.SDK_INT;
        if (version >= 19) {
            AppOpsManager manager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
            try {
                Class clazz = AppOpsManager.class;
                Method method = clazz.getDeclaredMethod("checkOp", int.class, int.class, String.class);
                return AppOpsManager.MODE_ALLOWED == (int) method.invoke(manager, op, Binder.getCallingUid(), context.getPackageName());
            } catch (Exception e) {
                Log.e(TAG, Log.getStackTraceString(e));
            }
        } else {
            Log.e(TAG, "Below API 19 cannot invoke!");
        }
        return false;
    }

    /**
     * 小米 ROM 权限申请
     */
    public static void applyMiuiPermission(Context context) {
        int versionCode = getMiuiVersion();
        if (versionCode == 5) {
            goToMiuiPermissionActivity_V5(context);
        } else if (versionCode == 6) {
            goToMiuiPermissionActivity_V6(context);
        } else if (versionCode == 7) {
            goToMiuiPermissionActivity_V7(context);
        } else if (versionCode == 8) {
            goToMiuiPermissionActivity_V8(context);
        } else {
            Log.e(TAG, "this is a special MIUI rom version, its version code " + versionCode);
        }
    }
    public static int getMiuiVersion() {
        String version = RomUtils.getSystemProperty("ro.miui.ui.version.name");
        if (version != null) {
            try {
                return Integer.parseInt(version.substring(1));
            } catch (Exception e) {
                Log.e(TAG, "get miui version code error, version : " + version);
                Log.e(TAG, Log.getStackTraceString(e));
            }
        }
        return -1;
    }
    private static boolean isIntentAvailable(Intent intent, Context context) {
        if (intent == null) {
            return false;
        }
        return context.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY).size() > 0;
    }

    /**
     * 小米 V5 版本 ROM权限申请
     */
    public static void goToMiuiPermissionActivity_V5(Context context) {
        Intent intent = null;
        String packageName = context.getPackageName();
        intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", packageName, null);
        intent.setData(uri);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (isIntentAvailable(intent, context)) {
            context.startActivity(intent);
        } else {
            Log.e(TAG, "intent is not available!");
        }

        //设置页面在应用详情页面
//        Intent intent = new Intent("miui.intent.action.APP_PERM_EDITOR");
//        PackageInfo pInfo = null;
//        try {
//            pInfo = context.getPackageManager().getPackageInfo
//                    (HostInterfaceManager.getHostInterface().getApp().getPackageName(), 0);
//        } catch (PackageManager.NameNotFoundException e) {
//            AVLogUtils.e(TAG, e.getMessage());
//        }
//        intent.setClassName("com.android.settings", "com.miui.securitycenter.permission.AppPermissionsEditor");
//        intent.putExtra("extra_package_uid", pInfo.applicationInfo.uid);
//        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        if (isIntentAvailable(intent, context)) {
//            context.startActivity(intent);
//        } else {
//            AVLogUtils.e(TAG, "Intent is not available!");
//        }
    }

    /**
     * 小米 V6 版本 ROM权限申请
     */
    public static void goToMiuiPermissionActivity_V6(Context context) {
        Intent intent = new Intent("miui.intent.action.APP_PERM_EDITOR");
        intent.setClassName("com.miui.securitycenter", "com.miui.permcenter.permissions.AppPermissionsEditorActivity");
        intent.putExtra("extra_pkgname", context.getPackageName());
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        if (isIntentAvailable(intent, context)) {
            context.startActivity(intent);
        } else {
            Log.e(TAG, "Intent is not available!");
        }
    }

    /**
     * 小米 V7 版本 ROM权限申请
     */
    public static void goToMiuiPermissionActivity_V7(Context context) {
        Intent intent = new Intent("miui.intent.action.APP_PERM_EDITOR");
        intent.setClassName("com.miui.securitycenter", "com.miui.permcenter.permissions.AppPermissionsEditorActivity");
        intent.putExtra("extra_pkgname", context.getPackageName());
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        if (isIntentAvailable(intent, context)) {
            context.startActivity(intent);
        } else {
            Log.e(TAG, "Intent is not available!");
        }
    }

    /**
     * 小米 V8 版本 ROM权限申请
     */
    public static void goToMiuiPermissionActivity_V8(Context context) {
        Intent intent = new Intent("miui.intent.action.APP_PERM_EDITOR");
        intent.setClassName("com.miui.securitycenter", "com.miui.permcenter.permissions.PermissionsEditorActivity");
//        intent.setPackage("com.miui.securitycenter");
        intent.putExtra("extra_pkgname", context.getPackageName());
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        if (isIntentAvailable(intent, context)) {
            context.startActivity(intent);
        } else {
            intent = new Intent("miui.intent.action.APP_PERM_EDITOR");
            intent.setPackage("com.miui.securitycenter");
            intent.putExtra("extra_pkgname", context.getPackageName());
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            
            if (isIntentAvailable(intent, context)) {
                context.startActivity(intent);
            } else {
                Log.e(TAG, "Intent is not available!");
            }
        }
    }
}
